# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))

# stdlib


#pyglet
from pyglet.gl import *

# cocos2d related
from cocos.layer import Layer, ColorLayer
from cocos.scene import Scene
from cocos.director import director
from cocos.actions import *

# tetrico related
from gamectrl import *
from gamemodel import *
from constants import *

__all__ = ['get_newgame']

class GameView( Layer ):

    def __init__(self, model):
        super(GameView,self).__init__()

        width, height = director.get_window_size()

        self.duration = 8

        self.position = ( width/2 - COLUMNS * SQUARE_SIZE / 2, 0 )
        self.transform_anchor = ( COLUMNS*SQUARE_SIZE /2, ROWS * SQUARE_SIZE/2)

        # background layer to delimit the pieces visually
        cl = ColorLayer( 112,66,20,50, width = width, height = height )
        self.add( cl, z=0)

        self.model = model
        
        self.model.push_handlers( self.on_move_bicho )

    def on_enter(self):
        super(GameView,self).on_enter()

    def on_exit(self):
        super(GameView,self).on_exit()

    def on_move_bicho(self ):
        print('moved bicho!!')
        return True

    def draw( self ):
        '''draw the map and the block'''

        glPushMatrix()
        self.transform()

        if self.model.bicho:
            self.model.bicho.draw()

        glPopMatrix()


def get_newgame():
    '''returns the game scene'''
    scene = Scene()

    # model
    model = GameModel()

    # controller
    ctrl = GameCtrl( model )
    ctrl.resume_controller()
    # view
    view = GameView( model )
    # set controller in model
    model.set_controller( ctrl )
    
    
    # add controller
    scene.add( ctrl, z=1, name="controller" )

    # add view
    scene.add( view, z=2, name="view" )

    return scene
